﻿using System;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Data.Linq;
using System.Threading;
using BSPortal.Data;
using DedeCMSModel;
using System.Data;

namespace DedeSyncService
{
    partial class DedeSync : ServiceBase
    {
        private Timer myTimer;

        public DedeSync()
        {
            InitializeComponent();
            WriteLog("SYS\t服务初始化");
            myTimer = new Timer(new TimerCallback(sync));
            myTimer.Change(TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(Int32.Parse(AppConfig.GetAppConfig("RTime"))));
            //延迟10秒，60分钟执行一次。
        }

        protected override void OnStart(string[] args)
        {
            WriteLog("SYS\t服务开始");
        }

        protected override void OnStop()
        {
            WriteLog("SYS\t服务停止");
            this.myTimer.Dispose();
        }

        private bool isExists(string userid)
        {
            var dbContext = new dedeEntities();
            IQueryable<Dede_member> members =from m in dbContext.Dede_members
                                                 where m.Userid==userid
                                                 select m;
            if (members.Any())
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private string GetPWD(string userid)
        {
            var dbContext = new dedeEntities();
            IQueryable<Dede_member> members = from m in dbContext.Dede_members
                                              where m.Userid == userid
                                              select m;
            if (members.Any())
            {
                return members.FirstOrDefault().Pwd.Trim();
            }
            else
            {
                return null;
            }

        }

        private Int32 getUnixTimeStamp()
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            DateTime dtNow = DateTime.Parse(DateTime.Now.ToString());
            TimeSpan toNow = dtNow.Subtract(dtStart);
            string timeStamp = toNow.Ticks.ToString();
            timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
            return Convert.ToInt32(timeStamp);
        }

        public void sync(object obj)
        {
            if (AppConfig.GetAppConfig("isPrint").Equals("1"))
                WriteLog(AppDomain.CurrentDomain.BaseDirectory);

            //ISession session = new Configuration().Configure(AppDomain.CurrentDomain.BaseDirectory+@"\hibernate.cfg.xml").BuildSessionFactory().OpenSession();
            //Windows Service下获取hibernate.cfg.xml有问题，通过AppDomain.CurrentDomain.BaseDirectory路径解决。
            var dbContext = new dedeEntities();

            string conn = "server=192.168.150.60;database=Baison_portal;uid=dbmanager;pwd=jyehFuV27FxNQ50tLOV0gglvPZ0=";
            Table<BSPortalUser> bsPortalUsers = BSPortal.Data.GetUserInfo.Get(conn);

            int num = 0;

            foreach (BSPortalUser portalUser in bsPortalUsers)
            {
                bool cmsUserisExist = isExists(portalUser.userid);

                if (portalUser.ustate.Equals(false))
                {
                    //用户为停用状态：
                    //1.存在于CMS中，停用CMS用户
                    //2.不存在于CMS中，不做处理；
                    if (cmsUserisExist)
                    {
                        Dede_member member = (from m in dbContext.Dede_members
                                              where m.Userid == portalUser.userid
                                              select m).FirstOrDefault();

                        member.Userid += "##";
                        member.Rank = 0;
                        member.Spacesta = -1;
                        
                        dbContext.SaveChanges();

                        num += 1;
                        WriteLog(string.Format("D\t账号:{0}停用\t第{1}个用户/共{2}个用户", portalUser.uname, num, bsPortalUsers.Count()));
                    }
                    else
                    {
                        num += 1;
                        WriteLog(string.Format("N\t账号:{0}无须处理\t第{1}个用户/共{2}个用户", portalUser.uname, num, bsPortalUsers.Count()));
                    }

                }
                else if (cmsUserisExist)
                {
                    //CMS中存在此用户，对比密码，相同不处理
                    if (portalUser.pwd.Trim().Equals(GetPWD(portalUser.userid)))
                    {
                        num += 1;
                        WriteLog(string.Format("N\t账号:{0}不做处理\t第{1}个用户/共{2}个用户", portalUser.uname, num, bsPortalUsers.Count()));
                    }
                    //CMS中存在此用户，对比密码，不相同则更新
                    else
                    {
                        Dede_member member = (from m in dbContext.Dede_members
                                              where m.Userid == portalUser.userid
                                              select m).FirstOrDefault();
                        member.Pwd = portalUser.pwd;

                        dbContext.SaveChanges();

                        num += 1;
                        WriteLog(string.Format("U\t账号:{0}密码更新\t第{1}个用户/共{2}个用户", portalUser.uname, num, bsPortalUsers.Count()));
                    }

                }
                else
                {
                    //用户不存在，插入
                    Dede_member member= new Dede_member();
                    
                    member.Mtype = portalUser.mtype;
                    member.Userid = portalUser.userid;
                    member.Uname = portalUser.uname;
                    member.Pwd = portalUser.pwd;
                    member.Sex = portalUser.sex;
                    member.Rank = (ushort)(portalUser.rank);
                    member.Money = (uint)(portalUser.money);
                    member.Email = portalUser.email;
                    member.Scores = uint.Parse(portalUser.scores);
                    member.Matt = ushort.Parse(portalUser.matt);
                    member.Spacesta = -10;
                    member.Face = "";
                    member.Safequestion = 0;
                    member.Safeanswer = "";
                    member.Joinip = "";
                    member.Loginip = "";
                    member.Exptime = 32767;
                    member.Uptime = getUnixTimeStamp();

                    try
                    {
                        dbContext.Add(member);
                        dbContext.SaveChanges();

                        num += 1;
                        WriteLog(string.Format("I\t账号:{0}插入\t第{1}个用户/共{2}个用户",portalUser.uname, num, bsPortalUsers.Count()));

                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(ex.Message);
                        WriteLog("E\t"+ex.Message);
                        throw;
                    }
                }
            }
            dbContext.ExecuteNonQuery("UP_MemberInit", CommandType.StoredProcedure, null);
            dbContext.SaveChanges();
            WriteLog("SYS\t同步完成");
        }
        
        public void WriteLog(string Log)
        {
            string logPath = AppDomain.CurrentDomain.BaseDirectory;
            if (!Directory.Exists(logPath+@"\log"))
            {
                Directory.CreateDirectory(logPath+@"\log");
            }

            StreamWriter dout = new StreamWriter(string.Format(logPath + @"\log\{0}.log",DateTime.Today.ToString("yyyy-MM-dd")), true);
            dout.Write("{0}\t"+Log+System.Environment.NewLine,System.DateTime.Now);
            dout.Close();
        }
        
    }
}
